<?php

namespace backend\controllers;

use backend\models\ProjectFilesDjr;
use backend\models\ProjectSingleAssetDjr;
use Yii;
use backend\models\ProjectSingle;
use backend\models\ProjectSingleSearch;
use backend\models\Tags;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use backend\models\ProjectDjr;
use backend\models\ProjectSingleDjr;
use backend\models\ProjectMappingDjr;
use yii\helpers\Url;

/**
 * ProjectSingleController implements the CRUD actions for ProjectSingle model.
 */
class ProjectSingleController extends Controller
{
    public $layout = 'yue-juan';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all ProjectSingle models.
     * @return mixed
     * @throws \yii\base\InvalidArgumentException
     */
    public function actionIndex()
    {
        if (Yii::$app->request->post('hasEditable')) {
            $model = $this->findModel(Yii::$app->request->post('editableKey'));
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $posted = current($_POST['ProjectSingle']);
            $post = ['ProjectSingle' => $posted];
            if ($model->load($post)) {
                $editableAttribute = Yii::$app->request->post('editableAttribute');
                if ($model->save()) {
//                    $out = ['output' => $model->$editableAttribute, 'message' => ''];
                    if ($editableAttribute == 'category') {
                        $output = Yii::$app->params['project_single_category'][$model->category];
                    } elseif ($editableAttribute == 'level') {
                        $output = Yii::$app->params['project_single_level'][$model->level];
                    } elseif ($editableAttribute == 'creditor') {
                        $output = preg_replace('/中国|资产管理股份有限公司/', '', $model->creditor);
                    } else {
//                        $output = $model->$editableAttribute;
                        $output = "<span title='" . $model->$editableAttribute . "' data-toggle='tooltip' data-placement='top'>" . mb_strcut($model->$editableAttribute, 0, 30) . "</span>";
                    }
                    $out = ['output' => $output, 'message' => ''];
                } else {
                    $out = ['output' => '', 'message' => serialize($model->getFirstErrors())];
                }
            } else {
                $out = ['output' => '', 'message' => 'not loaded'];
            }
            return $out;
        }

        $searchModel = new ProjectSingleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        $projectSingleDjrModel = new ProjectSingleDjr();
        $projectDjr = new ProjectDjr();
        $projectMappingDjr = new ProjectMappingDjr();
        $projectSingleAssetDjr = new ProjectSingleAssetDjr();
        $projectFileDjr = new ProjectFilesDjr();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'projectSingleDjrModel' => $projectSingleDjrModel,
            'projectDjr' => $projectDjr,
            'projectMappingDjr' => $projectMappingDjr,
            'projectSingleAssetDjr' => $projectSingleAssetDjr,
            'projectFileDjr' => $projectFileDjr,
        ]);
    }

    public function actionPublish2djr($id)
    {
        $model = $this->findModel($id);
        
        $projectSingleDjrModel = new ProjectSingleDjr();
        $projectDjr = new ProjectDjr();
        $projectMappingDjr = new ProjectMappingDjr();
        $projectSingleAssetDjr = new ProjectSingleAssetDjr();
        $projectFileDjr = new ProjectFilesDjr();
        
        return $this->render('_form_publish2djr', ['model' => $model, 'projectSingleDjrModel' => $projectSingleDjrModel, 'projectDjr' => $projectDjr, 'projectMappingDjr' => $projectMappingDjr, 'projectSingleAssetDjr' => $projectSingleAssetDjr, 'projectFileDjr' => $projectFileDjr,]);
    }

    /**
     * Displays a single ProjectSingle model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProjectSingle model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $post = Yii::$app->request->post();
        $model = new ProjectSingle();
        $tagModel = new Tags();
        if (Yii::$app->request->isAjax && $model->load($post)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }


        if ($model->load($post)) {
            $model->created_at = date('Y-m-d H:i:s');
            $model->owner = Yii::$app->user->id;
//            $model->city = $model->city ? implode(',', $model->city) : '';
            //自定义标签
            $tag_id = [];
            $arr_tags = explode('，', $model->tagTitle);
            unset($model->tagTitle);
            if (is_array($arr_tags) && count($arr_tags) > 0) {
                foreach ($arr_tags as $item) {
                    $cloneTagModel = clone $tagModel;
                    if ($item) {
                        if (Tags::find()->where(['title' => $item, 'user_id' => Yii::$app->user->id])->one() === null) {
                            $cloneTagModel->title = $item;
                            $cloneTagModel->user_id = Yii::$app->user->id;

                            $cloneTagModel->save();
                            $tag_id[] = $cloneTagModel->id;
                        } else {
                            Yii::$app->session->addFlash('warning', $item . '标签已存在');
                        }
                    }
                }
            }
            $model->tag = $model->tag ? array_merge($model->tag, $tag_id) : $tag_id;
            $model->tag = $model->tag ? implode(',', $model->tag) : '';

            if ($model->save()) {
                Yii::$app->session->setFlash('success', '创建成功');
                return $this->redirect(['index']);
            } else {
                Yii::$app->session->setFlash('warning', serialize($model->getFirstErrors()));
                if ($model->mortgage_type) {
                    $model->mortgage_type = explode(',', $model->mortgage_type);
                }
                return $this->redirect(Yii::$app->request->referrer);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProjectSingle model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $tagModel = new Tags();
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            //自定义标签
            $tag_id = [];
            $arr_tags = explode('，', $model->tagTitle);

            unset($model->tagTitle);
            if (is_array($arr_tags) && count($arr_tags) > 0) {
                foreach ($arr_tags as $item) {
                    $cloneTagModel = clone $tagModel;
                    if ($item) {
                        if (Tags::find()->where(['title' => $item, 'user_id' => Yii::$app->user->id])->one() === null) {
                            $cloneTagModel->title = $item;
                            $cloneTagModel->user_id = Yii::$app->user->id;

                            $cloneTagModel->save();
                            $tag_id[] = $cloneTagModel->id;
                        } else {
                            Yii::$app->session->addFlash('warning', $item . '标签已存在');
                        }
                    }
                }
            }

            $model->tag = $model->tag ? array_merge($model->tag, $tag_id) : $tag_id;
            $model->tag = $model->tag ? implode(',', $model->tag) : '';
            $model->updated_at = date('Y-m-d H:i:s');

            if ($model->save()) {
                Yii::$app->session->setFlash('success', '编辑成功');
                return $this->redirect(['index']);
            } else {
                Yii::$app->session->setFlash('warning', serialize($model->getFirstErrors()));
                return $this->render(Yii::$app->request->referrer);
            }
        }

        if ($model->tag) {
            $model->tag = explode(',', $model->tag);
        }

        $projectSingleDjr = new ProjectSingleDjr();
        $projectDjr = new ProjectDjr();
        $projectMappingDjr = new ProjectMappingDjr();
        $projectSingleAssetDjr = new ProjectSingleAssetDjr();
        $projectFileDjr = new ProjectFilesDjr();

        return $this->render('update', [
            'model' => $model,
            'projectSingleDjrModel' => $projectSingleDjr,
            'projectDjr' => $projectDjr,
            'projectMappingDjr' => $projectMappingDjr,
            'projectSingleAssetDjr' => $projectSingleAssetDjr,
            'projectFileDjr' => $projectFileDjr,

        ]);
    }

    /**
     * Deletes an existing ProjectSingle model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ProjectSingle model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProjectSingle the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProjectSingle::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }


    /**
     *
     */
    public function actionImport()
    {
        $project_file = $_FILES['project_file'];
        $filename = $project_file['name'];
        $ext = explode('.', basename($filename));
        $path = "uploads" . DIRECTORY_SEPARATOR . date('Ymd');
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $extension = array_pop($ext);
        if (!in_array($extension, ['xlsx', 'xls'])) {
            echo json_encode(['error' => '请上传.xls,.xlsx格式的文件']);
            return;
        }
        $target = $path . DIRECTORY_SEPARATOR . md5(uniqid('', true)) . "." . $extension;
        if (move_uploaded_file($project_file['tmp_name'], $target)) {
            $model = new ProjectSingle();
            $model->processData($target);
        } else {
            echo json_encode(['error' => '上传失败']);
            return;
        }
        return;
    }

    public function actionDownloadTemplate()
    {
        return Yii::$app->response->sendFile('project_single_import_template.xlsx');
    }

    /**
     *
     * @throws \yii\base\InvalidArgumentException
     */
    public function actionPublish($project_id = 0)
    {
        $projectDjrModel = new ProjectDjr();
        $projectSingleDjrModel = new ProjectSingleDjr();
        $projectMappingDjrModel = new ProjectMappingDjr();
        $projectSingleAssetDjr = new ProjectSingleAssetDjr();
        $projectFileDjrModel = new ProjectFilesDjr();

        $projectSingleModel = ProjectSingle::findOne($project_id);

        $post = Yii::$app->request->post();

        $multipleForm = Yii::$app->request->post('ProjectSingleAssetDjr', []);
        foreach ($multipleForm as $form) {
            $projectAssetDjrModels [] = clone $projectSingleAssetDjr;
        }

        $multipleFileForm = Yii::$app->request->post('ProjectFilesDjr', []);
        foreach ($multipleFileForm as $file) {
            $projectFileModels[] = clone $projectFileDjrModel;
        }

        if ($projectDjrModel->load($post) && $projectSingleDjrModel->load($post) && $projectMappingDjrModel->load($post) && $projectSingleAssetDjr->load($post) && $projectFileDjrModel->load($post)
            && Model::loadMultiple($projectAssetDjrModels, $post) && Model::loadMultiple($projectFileModels, $post)
        ) {
            $valid = $projectDjrModel->validate() && $projectSingleDjrModel->validate() && $projectMappingDjrModel->validate() && $projectSingleAssetDjr->validate() && Model::validateMultiple($projectAssetDjrModels) && Model::validateMultiple($projectFileModels);
            if ($valid) {
                //项目信息
                $project_values = [
                    'owner' => Yii::$app->user->id,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'reviewer' => Yii::$app->user->id,
                    'review_remark' => '通过APMS发布',
                    'review_time' => date('Y-m-d H:i:s'),
                    'rereviewer' => Yii::$app->user->id,
                    'rereview_remark' => '通过APMS发布',
                    'rereview_time' => date('Y-m-d H:i:s'),
                    'review' => 3,
                    'rereview' => 3,
                    'status' => 1,
                ];
                $projectDjrModel->attributes = $project_values;
                if ($projectDjrModel->save(false)) {
                    //修改原项目状态
                    $projectSingleModel->is_published = 1;
                    $projectSingleModel->save(false);

                    //
                    $projectSingleDjrModel->project_id = $project_id = $projectDjrModel->id;
                    $projectSingleDjrModel->price = $projectMappingDjrModel->sell_price;
                    $projectSingleDjrModel->project_tag = implode(',', array_merge($projectSingleDjrModel->project_tag_real ? $projectSingleDjrModel->project_tag_real : [], $projectSingleDjrModel->project_tag_personal ? $projectSingleDjrModel->project_tag_personal : [],
                        $projectSingleDjrModel->project_tag_intangible ? $projectSingleDjrModel->project_tag_intangible : [], $projectSingleDjrModel->project_tag_creditor ? $projectSingleDjrModel->project_tag_creditor : []));
                    unset($projectSingleDjrModel->project_tag_real, $projectSingleDjrModel->project_tag_personal, $projectSingleDjrModel->project_tag_intangible, $projectSingleDjrModel->project_tag_creditor);
                    $projectSingleDjrModel->save(false);

                    $projectMappingDjrModel->id = $project_id;
                    $projectMappingDjrModel->title_full = $projectDjrModel->title;
                    //上传项目缩略图和附件的目录
                    $path = "uploads_projects" . '/' . date('Ymd');
                    if (!@mkdir($path, 0777, true) && !is_dir($path)) {
                        Yii::info("创建目录失败。");
                    }

                    $thumb = $_FILES['ProjectMappingDjr'];
                    $temp = $thumb['tmp_name']['thumbnail'];
                    $random_name = md5(uniqid('', true));
                    $target_pc = $path . '/' . $random_name . '290x180' . strstr(basename($thumb['name']['thumbnail']), '.', false);
                    $target = $path . '/' . $random_name . strstr(basename($thumb['name']['thumbnail']), '.', false);
                    if (move_uploaded_file($temp, $target_pc)) {
                        $projectMappingDjrModel->thumbnail = Yii::$app->request->hostInfo . '/' . $target;
                    }
                    $projectMappingDjrModel->save(false);

                    //涉及的资产信息
                    foreach ($projectAssetDjrModels as $assetDjrModel) {
                        $assetValues = [
                            'project_id' => $project_id,
                            'price_total' => (double)$assetDjrModel->price_per_area * (double)$assetDjrModel->area,
                        ];
                        $assetDjrModel->attributes = $assetValues;
                        $assetDjrModel->save(false);
                    }
                    //上传附件
                    foreach ($projectFileModels as $key => $fileDjrModel) {
                        $files = $_FILES['ProjectFilesDjr'];
                        /** @var project files $fileValues */
                        $filenames = array_values($files['name']);
                        $file_temp_names = array_values($files['tmp_name']);
                        $temp_name = $file_temp_names[$key]['path'];
                        $filename = $filenames[$key]['path'];
                        $file_random_name = md5(uniqid('', true));

                        $target = $path . '/' . $file_random_name . strstr(basename($filename), '.', false);
                        $fileValues = [
                            'filename' => $filename,
                            'project_id' => $project_id,
                            'open_to_auth' => 1,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s'),
                        ];
                        if (move_uploaded_file($temp_name, $target)) {
//                            $fileValues['path'] = 'http://localhost:8006/' . $target;
//                            return json_encode(['path' => $target]);
//                            $re=file_get_contents('http://localhost:8006/' . Url::to(['project-files/get-remote-file','filename'=>$filename,'remote_url'=>Yii::$app->request->hostInfo.'/'.$target]));
//                            $re=file_get_contents('http://localhost:8006/index.php?r=project-files/get-remote-file&filename='.$filename.'&remote_url='.Yii::$app->request->hostInfo.'/'.$target);
//                            Yii::info($re);
                            $fileValues['path'] = Yii::$app->request->hostInfo . '/' . $target;
                            $fileDjrModel->attributes = $fileValues;
                            $fileDjrModel->save(false);
                        } else {
                            Yii::info("上传附件失败。");
                            continue;
                        }

                    }
                    Yii::$app->session->addFlash('success', '成功发布至点金人');
                } else {
                    Yii::$app->session->addFlash('warning', '发布失败');
                }
            } else {
                Yii::$app->session->addFlash('danger', serialize($projectDjrModel->getFirstErrors()) . serialize($projectSingleDjrModel->getFirstErrors()) . serialize($projectMappingDjrModel->getFirstErrors()));
            }
        } else {
            Yii::$app->session->addFlash('danger', '数据模型加载失败');
        }
        return $this->redirect(Yii::$app->request->referrer);
    }
}
